<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { Message } from '@element-plus/icons-vue'
import MessagePopup from './MessagePopup.vue'
import { getDoctorMessages } from '@/apis/doctor/doctorMessageAPI'

// 未读消息数
const unreadCount = ref(0)
// 消息弹窗显示状态
const showMessagePopup = ref(false)
// 轮询定时器
let pollingTimer: number | null = null

// 获取未读消息数
const fetchUnreadCount = async () => {
  try {
    const res = await getDoctorMessages({
      page: 1,
      pageSize: 1,
      status: 0 // 未读消息
    })
    if (res.code === 200) {
      unreadCount.value = res.data.unreadCount || 0
    }
  } catch (error) {
    console.error('获取未读消息数出错:', error)
  }
}

// 更新未读消息数
const updateUnreadCount = (count: number) => {
  unreadCount.value = count
}

// 打开消息弹窗
const openMessagePopup = () => {
  showMessagePopup.value = true
}

// 开始轮询
const startPolling = () => {
  // 每分钟轮询一次
  pollingTimer = window.setInterval(() => {
    fetchUnreadCount()
  }, 60000) // 60秒
}

// 组件挂载时获取未读消息数并开始轮询
onMounted(() => {
  fetchUnreadCount()
  startPolling()
})

// 组件卸载时清除轮询
onUnmounted(() => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = null
  }
})
</script>

<template>
  <div class="message-icon-container">
    <el-tooltip content="消息中心" placement="bottom">
      <el-badge :value="unreadCount > 0 ? unreadCount : ''" :hidden="unreadCount <= 0" class="badge-item">
        <el-icon class="header-icon" @click="openMessagePopup"><Message /></el-icon>
      </el-badge>
    </el-tooltip>

    <!-- 消息弹窗 -->
    <MessagePopup v-model:visible="showMessagePopup" @read="updateUnreadCount" />
  </div>
</template>

<style scoped lang="scss">
.message-icon-container {
  display: inline-flex;
  align-items: center;
  cursor: pointer;

  .header-icon {
    font-size: 20px;
    color: #606266;
    transition: color 0.3s;

    &:hover {
      color: var(--el-color-primary);
    }
  }

  :deep(.el-badge__content) {
    background-color: var(--el-color-danger);
  }
}
</style>
